<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        span{
            position: absolute;
            display: block;
            width: 200px;
            height: 100px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <button>dianji</button>
    <div></div>
    <span></span>
    <script>
        function animate(obj, target) {
            // 当我们不断点击按钮 元素速度会越来越快 因为开启了太多的定时器
            // 所以只让一个定时器执行 先清除之前的定时器 只保留一个定时器
            clearInterval(obj.timer)
            obj.timer = setInterval(function () {
                if (obj.offsetLeft >= target) {
                    // 停止动画的本质 就是停止定时器
                    clearInterval(obj.timer)
                }
                obj.style.left = obj.offsetLeft + 1 + 'px'
            }, 1)
        }
        var div = document.querySelector('div');
        var span = document.querySelector('span');
        var button = document.querySelector('button');
        animate(div,200)
        button.addEventListener('click',function(){
            animate(span,400)
        })
    </script>
</body>

</html>